import { NextRequest, NextResponse } from 'next/server'
import { getServerSession } from 'next-auth'
import { authOptions } from '@/lib/auth'
import { cookies } from 'next/headers'
import prisma from '@/lib/prisma'

export async function POST(req: NextRequest) {
  const requestId = req.nextUrl.searchParams.get('requestId') || 'unknown'
  console.log(`[${requestId}] 接收到注销所有设备请求`)
  
  try {
    const session = await getServerSession(authOptions)
    
    if (!session?.user) {
      console.log(`[${requestId}] 用户未登录，拒绝注销请求`)
      return NextResponse.json(
        { error: '用户未登录' },
        { status: 401 }
      )
    }
    
    const userId = session.user.id
    const userEmail = session.user.email
    console.log(`[${requestId}] 执行在所有设备上注销用户: ${userId}, 邮箱: ${userEmail}`)
    
    // 尝试从数据库删除用户的会话（如果使用数据库会话）
    try {
      // 1. 尝试删除 Session 表中的会话
      const deletedSessions = await prisma.session.deleteMany({
        where: {
          userId: userId
        }
      })
      console.log(`[${requestId}] 从数据库删除了 ${deletedSessions.count} 个会话`)
      
      // 2. 尝试删除 Account 表相关的刷新令牌（可选）
      const updatedAccounts = await prisma.account.updateMany({
        where: {
          userId: userId
        },
        data: {
          refresh_token: null,
          access_token: null,
          expires_at: 0
        }
      })
      
      if (updatedAccounts.count > 0) {
        console.log(`[${requestId}] 重置了 ${updatedAccounts.count} 个账号的令牌`)
      }
    } catch (dbError) {
      // 数据库操作失败只记录错误，不中断流程
      console.error(`[${requestId}] 数据库操作失败:`, dbError)
    }
    
    // 清除所有相关的会话cookie
    const cookieStore = cookies()
    
    // 获取所有cookie
    const allCookies = cookieStore.getAll()
    console.log(`[${requestId}] 找到${allCookies.length}个cookie`)
    
    // 记录所有cookie名称，方便调试
    const cookieNames = allCookies.map(c => c.name).join(', ')
    console.log(`[${requestId}] 所有cookie名称: ${cookieNames}`)
    
    // 清除所有与认证相关的cookie
    let deletedCount = 0
    for (const cookie of allCookies) {
      try {
        if (cookie.name.includes('next-auth') || 
            cookie.name.includes('csrf') || 
            cookie.name.includes('session')) {
          console.log(`[${requestId}] 删除服务器端cookie: ${cookie.name}`)
          cookieStore.delete(cookie.name)
          deletedCount++
        }
      } catch (e) {
        console.error(`[${requestId}] 删除cookie ${cookie.name} 失败:`, e)
      }
    }
    
    console.log(`[${requestId}] 已删除 ${deletedCount} 个服务器端cookie`)
    
    // 创建响应
    const response = NextResponse.json({ 
      success: true,
      message: '您已成功注销，所有设备需要重新登录',
      requestId: requestId,
      timestamp: new Date().toISOString(),
      userId: userId,
      email: userEmail
    }, { status: 200 });
    
    // 确保清除所有常见的认证相关cookie，设置为过期
    const cookiesToClear = [
      'next-auth.session-token',
      '__Secure-next-auth.session-token',
      '__Host-next-auth.session-token',
      'next-auth.callback-url',
      'next-auth.csrf-token',
      '__Host-next-auth.csrf-token',
      '__Secure-next-auth.csrf-token',
      'next-auth.pkce.code_verifier',
      'next-auth.state',
      'next-auth.signin',
      'next-auth.session' 
    ];
    
    console.log(`[${requestId}] 开始在客户端设置过期cookie`)
    
    // 为不同的路径设置过期cookie
    const paths = ['/', '/api', '/api/auth'];
    
    for (const cookieName of cookiesToClear) {
      try {
        // 为每个路径都设置过期cookie
        paths.forEach(path => {
          // 常规版本
          response.cookies.set(cookieName, '', { 
            expires: new Date(0),
            path: path,
            maxAge: 0,
            sameSite: 'lax'
          });
          
          // 安全版本
          if (cookieName.includes('next-auth')) {
            response.cookies.set(`__Secure-${cookieName}`, '', { 
              expires: new Date(0),
              path: path,
              maxAge: 0,
              secure: true,
              sameSite: 'lax'
            });
            
            response.cookies.set(`__Host-${cookieName}`, '', { 
              expires: new Date(0),
              path: path,
              maxAge: 0,
              secure: true,
              sameSite: 'lax'
            });
          }
        });
      } catch (e) {
        console.error(`[${requestId}] 设置过期cookie ${cookieName} 失败:`, e)
      }
    }
    
    // 设置响应头，确保不会缓存
    response.headers.set('Cache-Control', 'no-store, no-cache, must-revalidate, proxy-revalidate');
    response.headers.set('Pragma', 'no-cache');
    response.headers.set('Expires', '0');
    response.headers.set('X-Request-ID', requestId);
    response.headers.set('X-Auth-Status', 'logged-out');
    response.headers.set('X-Auth-User', userEmail);
    response.headers.set('X-Auth-Time', new Date().toISOString());
    
    console.log(`[${requestId}] 注销所有设备处理完成，返回响应`)
    
    return response;
  } catch (error) {
    console.error(`[${requestId}] 注销所有设备失败:`, error)
    
    const errorResponse = NextResponse.json(
      { 
        error: '注销所有设备失败', 
        details: error instanceof Error ? error.message : '未知错误',
        requestId: requestId,
        timestamp: new Date().toISOString()
      },
      { 
        status: 500,
        headers: {
          'Cache-Control': 'no-store, no-cache, must-revalidate, proxy-revalidate',
          'Pragma': 'no-cache',
          'Expires': '0',
          'X-Request-ID': requestId,
          'X-Auth-Status': 'error'
        }
      }
    )
    
    return errorResponse;
  }
} 